<script setup>
import { ElMessage } from 'element-plus';
import { onMounted, reactive} from 'vue';
import router from '@/routes';

const cart = reactive({
      cartItem:[],
      subTotal: 0.0,
})

const products = [
    {
        productID:'RP-LI-02',
        name: 'dog'
    }
]

// let quantity = ref(1)
// let subTotal = ref(100)
const editQuantity = (newValue, oldValue, index) =>{
    let cItem = cart.cartItem[index]
    //更新 单种商品 新的数量 和总价
    cItem.quantity = newValue
    cItem.total = cItem.item.listPrice * cItem.quantity

    //更新购物车
    cart.cartItem[index] = cItem
    updateCart(cart)
}

// const alterData = () =>{
//     row[column.property + 'isShow'] = false
// }

const deletes = (index) => {
    console.log(index)
    ElMessageBox.confirm(
    "是否移出购物车","提示",
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(()=>{
    removeCartItem(index)
    ElMessage({
        type: 'success',
        message: '删除成功',
      })
  }).catch(() =>{
    //取消删除
  })
}

const removeCartItem = (index) =>{
    //删除购物车中某个商品时，需要修改 总计价格
    // cart.subTotal -= cart.cartItem[index].total
    cart.cartItem.splice(index, 1)
    
    updateCart(cart)
}
// const getItem = (async (itemID)=>{
//   const [err, res] = await CatalogService.promise_process(CatalogService.getItem(itemID));
//   if(err){
//     console.log(err)
//     ElMessage({
//       message: '请求服务器失败',
//       type: 'error',
//     })
//   }
//   if(res){
//     if (sessionStorage.getItem("itemList") == null){
//       let itemList = []
//       let item = res.data
//       itemList.push(item)
//       sessionStorage.setItem("itemList",JSON.stringify(itemList))
//       cartData.value=itemList
//       // alert(JSON.stringify(cartData.value))
//     }
//     else{
//       let temp = sessionStorage.getItem("itemList")
//       let itemList = JSON.parse(temp)
//       // alert(itemList)
//       let item = res.data
//       itemList.push(item)
//       // alert(itemList)
//       sessionStorage.setItem("itemList",JSON.stringify(itemList))
//       cartData.value=itemList
//       // alert(JSON.stringify(cartData.value))
//     }
//   }
// })

// const init = ()=>{
//   let itemId = route.query.itemId;
//   if(itemId == null){
//     let temp = sessionStorage.getItem("itemList")
//     let itemList = JSON.parse(temp)
//     cartData.value=itemList
//   }
//   else
//     getItem(itemId)
// }

const getCart = () =>{
    let sessionCart = JSON.parse(sessionStorage.getItem('cart'))
    if(sessionCart != null){
        cart.cartItem = sessionCart.cartItem
        cart.subTotal = sessionCart.subTotal
    }
    else {
        sessionStorage.setItem('cart', JSON.stringify(cart))
    }
    // console.log(JSON.stringify(cart))
}

const updateCart = (cart) =>{
    cart.subTotal = 0
    cart.cartItem.forEach((cItem) =>{
        cart.subTotal += cItem.total
    })
    sessionStorage.setItem('cart', JSON.stringify(cart))
}

const openClearCart = () =>{
    ElMessageBox.confirm(
    "清空购物车","提示",
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(()=>{
    clearCart()
    ElMessage({
        type: 'success',
        message: '清空购物车成功',
      })
  }).catch(() =>{
    //取消删除
  })
}

const clearCart = () => {
    cart.cartItem = []
    cart.subTotal = 0
    sessionStorage.setItem('cart', JSON.stringify(cart))
}

onMounted(()=>{
    //页面加载周期，从session中获取购物车，并赋给cart，如果session中不存在，存入一个空的cart
    getCart()
})

</script>

<template>
    <top />
    <div class="cart">
        <li>我的购物车</li>
    </div>
<el-card>
    <el-table
        :data="cart.cartItem"
        height="300"
        style="width: 100%">

        <el-table-column prop="item.itemId" label="itemID" ></el-table-column>
        <el-table-column prop="item.productId" label="商品号" ></el-table-column>
        <el-table-column prop="item.attribute1" label="描述" min-width="100"></el-table-column>
        <el-table-column  label="有无存货">
            <template #default="scope">
                <span>
                    <el-tag>
                        {{scope.row.item.quantity > scope.row.quantity? "是" : "否"}}</el-tag>
                </span>
            </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" min-width="150">
            <template #default="scope">
                <el-input-number type="number" v-model="scope.row.quantity" min="1" 
                @change="(newValue, oldValue,)=>{editQuantity(newValue, oldValue, scope.$index)}"/>
            </template>
        </el-table-column>
        <el-table-column prop="item.listPrice" label="单价" ></el-table-column>
        <el-table-column prop="total" label="总价格" ></el-table-column>
        <el-table-column fixed="right" label="操作" >
        <template #default="scope">
                <el-button type="warning" round size="small" @click="deletes(scope.$index)">移出</el-button>
        </template>
        </el-table-column>
    </el-table>
    <el-row :gutter="0">
    <el-col :span="4">
        <div><el-button type="warning" round size="small" @click="openClearCart">清空购物车</el-button> </div>
    </el-col>
    <el-col :span="8" :offset="4">
        <div>合计共：￥{{cart.subTotal}}</div>
    </el-col>
    <el-col :span="4">
        <div><el-button type="primary" round size="small" @click="getCart">更新</el-button> </div>
    </el-col>
    <el-col :span="4">
        <div><el-button type="success" round size="small" @click="router.push({name:'addOrder'})">去结算</el-button> </div>
    </el-col>
    </el-row>
</el-card>
    <!-- <el-card class="petLike">
        <p style="font-family: 'Californian FB'">Pet Favorites <br/>
            Shop for more of your favorite pets here.</p>
        <ul>
            <template v-for="product in products">
                <li><a href="/product?productId={{product.productID}}">{{product.name}}</a>({{product.productID}}) </li>
            </template>
        </ul>
    </el-card> -->
<bottom />
</template>
<style scoped>
.cart {
    width: 90%;
    margin: 0 auto;
    color: silver;
    justify-content: center;
    border-bottom: 1px solid #704747;
}
.cart li {
    text-align: center;
    height: 50px;
    font-size: 30px;
    line-height: 50px;
    color: #2881ff;
}

.petLike{
    position: fixed;
    top:25%;
    left: 0;
    width: 18%;
    height: 50%;
}
</style>
